<template>
  <div class="taskwrap oh">
    <h3 class="mb34 mt18 f20 pageTitle">全局数据</h3>
    <div>
      <div class="ifc simulate f0">
        <div>
          <span class="bg ib case" :style="{ 'background-image': 'url(' + box + ')' }"></span>
        </div>
        <div class="ml32 h">
          <div class="f36 count">{{ statData.complete || 0 }}</div>
          <div class="status mt15">已完成仿真数</div>
        </div>
        <div class="ml30 h">
          <span class="bg w15 h16 ib" :style="{ 'background-image': 'url(' + arrow + ')' }"></span>
        </div>
      </div>

      <div class="ifc simulate f0 order ml44">
        <div>
          <span class="bg ib case" :style="{ 'background-image': 'url(' + order + ')' }"></span>
        </div>
        <div class="ml32 h">
          <div class="f36 count">{{ statData.running || 0 }}</div>
          <div class="status mt15">未完成仿真数</div>
        </div>
        <div class="ml30 h">
          <span class="bg w15 h16 ib" :style="{ 'background-image': 'url(' + arrow + ')' }"></span>
        </div>
      </div>
    </div>
    <div class="tb">
      <div class="fx sb">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">

          <el-form-item label="" style="max-width: 248px">
            <el-date-picker v-model="formInline.daterange" type="daterange" range-separator="到"
              start-placeholder="请选择日期" end-placeholder="请选择日期" :size="size" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="" style="max-width: 139px">
            <el-select v-model="formInline.status" placeholder="请选择状态" clearable :suffix-icon="CaretBottom">
              <el-option label="异常" value="0" />
              <el-option label="初始化" value="3" />
              <el-option label="进行中" value="1" />
              <el-option label="完成" value="2" />

            </el-select>
          </el-form-item>
          <el-form-item label="" style="max-width: 235px">
            <el-input :maxlength="50" v-model="formInline.name" @keyup.enter="handleSubmit" placeholder="请输入任务名称"
              clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" class="searchbtn">搜索</el-button>
          </el-form-item>
        </el-form>
        <div class="">
          <el-button type="primary" @click="linkTo('/simulate')" class="addbtn">新增</el-button>
        </div>
      </div>
      <div ref="recordTable" style="overflow: hidden;" :style="{ width: tableWidth }">
        <el-table :data="records" :fit="true" :style="{ width: '100%' }">
          <el-table-column type="selection" width="56" />
          <el-table-column label="任务ID" min-width="270" prop="id" :sortable="true" />
          <el-table-column label="任务名称" min-width="320" prop="name" :sortable="true" />
          <el-table-column label="任务状态" min-width="100" prop="status">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-tag class="ml-2" type="danger" v-if="scope.row.status == 0">异常</el-tag>
                <el-tag class="ml-2" type="info" v-if="scope.row.status == 1">进行中</el-tag>
                <el-tag class="ml-2" type="success" v-if="scope.row.status == 2">完成</el-tag>
                <el-tag class="ml-2" type="info" v-if="scope.row.status == 3">初始化</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="耗时" min-width="150" prop="timeRunning" />


          <el-table-column label="软件类型" min-width="80" prop="name">
            <template #default="scope">
              {{ scope.row.appId == '1' ? 'abaqus' : '' }}
              {{ scope.row.appId == '2' ? 'comsol' : '' }}
              {{ scope.row.appId == '3' ? 'ansys' : '' }}
              {{ scope.row.appId == '4' ? 'fastcae' : '' }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" min-width="240" prop="createTimeStr" :sortable="true" />
          <el-table-column label="修改时间" min-width="240" prop="updateTimeStr" :sortable="false" />
          <el-table-column label="操作" min-width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" :disabled="scope.row.status != 0 && scope.row.status != 2"
                @click="handleView(scope.$index, scope.row)">查看</el-button>
              <el-button size="small" :disabled="scope.row.status != 2"
                @click="handleDownload(scope.row)">导出</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              <!--               <a href="http://10.1.1.9:8090/taskComputeResult/downloadOdb/4efedfd4f7584552b13563dba133920b">导出</a>
 -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="demo-pagination-block b tc fc bb pt20 pb40">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10]" :small="small"
          :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
  <!-- 展示弹窗开始 -->
  <el-dialog v-model="dialogFormVisible" title="结果展示" width="90%" :before-close="handleClose">
    <div>
      <div>
        <el-form :inline="true" :model="subTask" class="demo-form-inline">
          <el-row>
            <el-col :span="8">
              <el-form-item label="任务名称" style="width: 90%" label-width="60">
                <el-input v-model="subTask.name" readonly placeholder="请输入任务名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="仿真软件" style="width: 90%" label-width="60">
                <el-input v-model="subTask.appName" readonly placeholder="请输入仿真软件" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="仿真模块" style="width: 100%" label-width="60">
                <el-input v-model="subTask.appModuleName" readonly placeholder="请输入仿真模块" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="bb pd30" style="min-height: 634px">
        <div v-if="isPicResult">
          <VtkView ref="vtkViewDom" v-if="isShowVtk" />
          <img v-else :src="resultImage" class="b h" style="background-color: #f0f3f7" />
        </div>
        <div v-else>
          <el-text class="mx-1" type="danger">{{ subTaskErrorMsg || '暂无异常信息' }}</el-text>
        </div>
      </div>
    </div>
  </el-dialog>
  <!-- 展示弹窗结束 -->
</template>
<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import box from '@/assets/images/box.png'
import arrow from '@/assets/images/arrow.png'
import order from '@/assets/images/order.png'
import { CaretBottom } from '@element-plus/icons-vue'
import { getSubTask, selectAppParamTree, deleteSubTask, getNumber, getResultPic, getResultErrorMsg, downFile } from '../api/task'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'
import hostName from '@/utils/hostName'
import useSidebarStatusStore from '../stores/sidebarContrl'
import VtkView from "../components/vtkView/Index.vue"
import registerStore from '../stores/index'
const { viewsModulesPinia, toolModulePinia } = registerStore();
const vtkViewDom = ref(null)
const sidebarStatusStore = useSidebarStatusStore()
const isCollapse = computed(() => {
  return sidebarStatusStore.isCollapse
})

const router = useRouter()
const dialogFormVisible = ref(false)
const size = ref('')
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const disabled = ref(false)
const background = ref(false)
const recordTable = ref()

// 控制弹窗是否显示图片
const isPicResult = ref(true)

// 显示错误信息
const subTaskErrorMsg = ref('')

const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  getAppParamTree()
}
//表格宽度
const tableWidth = computed(() => {
  if (isCollapse.value) {
    return 'calc(100vw - 140px)'
  } else {
    return 'calc(100vw - 100px)'
  }
})


//搜索表单
const formInline = reactive({
  daterange: [],
  name: '',
  status: '',
})

let param = {
  endTime: null,
  name: null,
  startTime: null,
  status: null,
  subTaskId: '',
  taskId: '',
  userId: '',
}

//提交搜索列表
function handleSubmit() {
  console.log('formInline', formInline)
  let newobj = {
    endTime: formInline.daterange && formInline.daterange.length > 0 ? formInline.daterange[1] : null,
    name: formInline.name,
    startTime: formInline.daterange && formInline.daterange.length > 0 ? formInline.daterange[0] : null,
    status: formInline.status,
  }
  param = { ...param, ...newobj }
  getAppParamTree()
}

//计算耗时时间
function convertTimestampDiffToHMS(timestampDiff) {
  var seconds = Math.floor(timestampDiff / 1000);
  var day = Math.floor(seconds / 3600 / 24);
  var hours = Math.floor(seconds / 3600 % 24);
  var minutes = Math.floor((seconds % 3600) / 60 % 60);
  var remainingSeconds = seconds % 60;
  //return day+'天'+hours+ "小时"+minutes + "分钟"+remainingSeconds + "秒"
  return (day > 0 ? (day + '天') : '') + (hours > 0 ? (hours + "小时") : '') + (minutes > 0 ? (minutes + "分钟") : '') + (remainingSeconds > 0 ? (remainingSeconds + "秒") : '');
}


const records = ref([]) //表格数据

//获取列表数据
function getAppParamTree() {
  selectAppParamTree(currentPage.value, pageSize.value, param).then((res) => {
    records.value = res.data.records
    currentPage.value = res.data.current
    total.value = res.data.total
    //records.value[0].createTime = '2024-01-09T10:22:13'//测试
    //records.value[0].status = 1//测试
    records.value.map(item => {
      if ((new Date()).valueOf() - (new Date(item.createTime)).valueOf() <= 0) {
        //如果本地缓存中已经有保存创建时间就从本地中获取
        if (localStorage.getItem('task:' + item.id)) {
          item.createTimeStamp = localStorage.getItem('task:' + item.id)
        } else {
          item.createTimeStamp = (new Date()).valueOf()
          //当服务器的新建时间比客户端当前时间要先时，把任务对应的客户端时间记录到localStoreage中
          localStorage.setItem('task:' + item.id, item.createTimeStamp)
        }

      } else {
        item.createTimeStamp = (new Date(item.createTime)).valueOf()
      }
    })
    setInterval(() => {
      records.value.map(item => {
        let timeDiff = (new Date()).valueOf() - item.createTimeStamp
        if (item.status == 1) {
          item.timeRunning = convertTimestampDiffToHMS(timeDiff)
        } else {
          item.timeRunning = null
        }
      })
    }, 1000)
  })
}

const subTask = ref({}) //子任务数据
const isShowVtk = ref(true)
const vtkURL = ref('')
const vtuArr = ref([])
const vtuType = ref(null)

//查看子任务
const handleView = (index, row) => {
  dialogFormVisible.value = true
  console.log(index, row)
  getSubTask(row.id).then((res) => {
    subTask.value = res.data
    // 如果为异常，则显示错误信息
    if (res.data.status == 0) {
      isPicResult.value = false
      handleFetchResultErrorMsg(res.data.id)
    } else {
      let taskComputeResult = null
      if (typeof res.data == 'object') {
        taskComputeResult = res.data.taskComputeResult
      } else if (typeof res.data == 'string') {
        let data = JSON.parse(res.data)
        taskComputeResult = data.taskComputeResult
      }
      vtuArr.value = taskComputeResult ? taskComputeResult.vtu ? strToArr(taskComputeResult.vtu) : [] : [];
      vtuType.value = taskComputeResult ? taskComputeResult.vtuType : null;
      //debug;
      console.log('localStorage.', localStorage.auth_token)
      let token = localStorage.getItem('auth_token');
      // 如果为成功，则显示结果图片
      isPicResult.value = true;
      if (token && taskComputeResult) {

        resultImage.value = `${taskComputeResult.picUrl}&token=${token}`
        if (vtuType.value === 1 || vtuType.value === 2) {
          vtkURL.value = taskComputeResult.resultUrl
        } else if (vtuType.value === 3) {
          vtkURL.value = taskComputeResult.taskResultVtu.vtuUrl
        }
        console.log('substring', vtkURL.value.substring(vtkURL.value.length - 3, vtkURL.value.length))
        if (vtkURL.value.substring(vtkURL.value.length - 3, vtkURL.value.length) == 'vtk') {
          vtkURL.value += '&token=${token}&a.vtk'
        } else if (vtkURL.value.substring(vtkURL.value.length - 3, vtkURL.value.length) == 'vtu') {
          vtkURL.value += '&token=${token}&a.vtu'
        }

      } else {
        resultImage.value = taskComputeResult ? taskComputeResult.picUrl : '';
        vtkURL.value = taskComputeResult ? taskComputeResult.resultUrl : '';
      }
      console.log('vtkURL.value', vtkURL.value);
      //添加测试模型连接
      //vtkURL.value = 
      //vtkURL.value = 'http://localhost:6001/aa.vtk?toen=666&y.vtk' //http://localhost:6001/fastCAE/assets/vtk/aa.vtk
      //'http://10.1.1.43:9000/cae/mesh6-ef60ffc094dc42a0b5377b9521f2c8aa .vtk' //'http://10.1.1.43:9000/cae/mesh5-ae6171452d03496c950898e46a5b8946 .vtk' //
      if (vtkURL.value && vtuArr.value.length === 0 && vtuType.value === 1) {
        // 加载单个模型
        isShowVtk.value = true
        viewsModulesPinia.urlLoadData(vtkURL.value).then((res) => {
          viewsModulesPinia.setLoadingIsOk(true)
          viewsModulesPinia.setLoadingModel(false)
        }).catch((e) => {
          console.log('err', e)
          // 加载多个模型
          viewsModulesPinia.setLoadingModel(false)
          viewsModulesPinia.setLoadingIsOk(false)
        })
      } else if (vtkURL.value && vtuArr.value.length && vtuType.value === 2) {
        renderVtkModelsFn(vtkURL.value, vtuArr.value)
      } else {
        isShowVtk.value = false
      }
      // handleFetchResultPic(res.data.computeResultId)

    }
  }).catch((err) => {
    isShowVtk.value = false
    viewsModulesPinia.setLoadingModel(false)
    viewsModulesPinia.setLoadingIsOk(false)
  })
}

// 将vtu字符转数组
const strToArr = (str) => {
  // const newString = str.substring(1, str.length - 1);
  const arr = str.split(",");
  return arr ? arr : []
}

// 渲染多个vtk的项目
const renderVtkModelsFn = (path, vtuArr) => {
  const vtkPromiseArr = []
  vtuArr.forEach((item, index) => {
    const url = path + item
    const onePro = viewsModulesPinia.urlLoadData(url);
    vtkPromiseArr.push(onePro)
  })
  Promise.allSettled(vtkPromiseArr).then((res) => {
    console.log('模型全部加载完成', res);
    isShowVtk.value = true
    viewsModulesPinia.setLoadingIsOk(true)
    viewsModulesPinia.setLoadingModel(false)
  }).catch(() => {
    console.log('报错但是全部加载完成', res);
    viewsModulesPinia.setLoadingModel(false)
    viewsModulesPinia.setLoadingIsOk(false)
  })
}

//获取子任务错误信息
function handleFetchResultErrorMsg(id) {
  getResultErrorMsg(id).then((res) => {
    subTaskErrorMsg.value = res.message
  })
}

// 获取仿真任务完成情况统计数据
// function statistics () {

// }

// const handleFetchResultErrorMsg = (id) => {
// 	getResultErrorMsg(id).then((res) => {
// 		subTaskErrorMsg.value = res.message
// 		console.log('result error', res.message)
// 	})
// }

//删除任务
function handleDelete(index, row) {
  ElMessageBox.confirm('你是否确定删除本任务', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteSubTask(row.id).then((res) => {
        getAppParamTree()
      })
    })
    .catch(() => { })
}
//前往跳转
function linkTo(route) {
  router.push(route)
}



const handleClose = () => {
  console.log('close')
  subTaskErrorMsg.value = ''
  isPicResult.value = true
  dialogFormVisible.value = false
  if (vtkViewDom.value) {
    viewsModulesPinia.modelActorArr.forEach((item, index) => {
      toolModulePinia.removeActor(index)
      vtkViewDom.value.closeInit(index)
    })
    viewsModulesPinia.initModelActorArr()
  }
}

const statData = ref({})
//获取仿真任务完成情况统计数据
function statistics() {
  getNumber().then((res) => {
    res.data.map((item, index) => {
      statData.value[item.label] = item.count
    })
  })
}
//下载结果文件,根据不同环境选择下载方式
function handleDownload(row) {
  if ((window.chrome && window.chrome.webview) || (window.qt && window.sendObject)) {
    let fileUrl = row.taskComputeResult.resultUrl
    downFile({ fileUrl })
  } else {
    window.location.href = hostName + '/taskComputeResult/downloadOdb/' + row.id
  }
}

const resultImage = ref(null)
//查看仿真结果
function handleFetchResultPic(id) {
  getResultPic(id).then((res) => {
    resultImage.value = 'data:image/png;base64,' + res.data
  })
}

//清除本地缓存中记录的创建时间超过2天的数据
function clearLocalTaskData() {
  for (let i in localStorage) {
    if (/^task:/.test(i)) {
      let diff = ((new Date()).valueOf() - parseInt(localStorage[i])) / (1000 * 60 * 60 * 24)
      console.log('diff', diff)
      if (diff > 3) {
        localStorage.removeItem(i)
      }
    }
  }
}

onMounted(() => {
  getAppParamTree()
  statistics()
  clearLocalTaskData()
})
</script>
<style lang="scss">
.el-form-item__label {
  height: 40px;
  line-height: 40px;
  justify-content: flex-start !important;
}

.el-dialog__close {
  display: inline-flex;
  width: 21px;
  align-items: center;
  justify-content: center;
  height: 21px;
  border-radius: 50%;
  background-color: #f56c6c;
  color: #fff !important;
}

.taskwrap {
  width: 100%;
  /*height: calc(100vh - 72px);*/
  padding-right: 33px;

  .addbtn {
    width: 60px;
    height: 35px;
    opacity: 1;
    background: rgba(103, 194, 58, 1);
  }

  .addbtn:hover {
    background: #8bd667;
  }
}

.tb th {
  background-color: #f2f6fc !important;
}

.searchbtn {
  background: rgba(0, 179, 255, 1);
}

.searchbtn:hover {
  background: #5ac9fa;
}

.tb {
  border-radius: 5px;
  margin-top: 33px;
  background-color: #fff;
  padding-top: 13px;
  height: auto;
  box-sizing: border-box;
  padding-left: 20px;
  padding-right: 20px;
  box-shadow: 0px 0px 30px rgba(30, 38, 76, 0.1);
}

.order {
  background: linear-gradient(229.09deg, rgba(116, 109, 255, 1) 0%, rgba(177, 125, 255, 1) 100%) !important;
}

.order.case {
  width: 60px !important;
  height: 49.5px !important;
}

.taskwrap {
  box-sizing: border-box;
  padding: 20px;
}

.status {
  font-size: 13px;
  color: #fff;
}

.count {
  color: #fff;
  line-height: 1;
}

.case {
  width: 54px;
  height: 49.5px;
}

.simulate {
  min-width: 271px;
  height: 114px;
  opacity: 1;
  border-radius: 5px;
  background: linear-gradient(134.01deg, rgba(0, 226, 196, 1) 0%, rgba(0, 191, 255, 1) 100%);
  box-shadow: 0px 2px 5px rgba(79, 98, 255, 0.05);
  padding: 22px 30px;
  box-sizing: border-box;
}
</style>
